﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using wp8nop.ViewModel;
using wp8nop.Model;
using Microsoft.Practices.ServiceLocation;
using System.Diagnostics;
using GalaSoft.MvvmLight.Messaging;
using System.Windows.Media;
using System.Collections;

namespace wp8nop
{
    public partial class ProdottiList : PhoneApplicationPage
    {
        ProdottiListViewModel vm;

        public ProdottiList()
        {
            InitializeComponent();

            vm = (ProdottiListViewModel)this.DataContext;
            vm.OnOpenDettaglioProdotto += vm_OnOpenDettaglioProdotto;
            this.Loaded += ProdottiList_Loaded;
        }

        void vm_OnOpenDettaglioProdotto(object sender, Model.ProdottoViewModel e)
        {
            OpenDettagioProdotto(e);
        }

        void OpenDettagioProdotto(ProdottoViewModel prod)
        {
            var dettProd = ServiceLocator.Current.GetInstance<DettaglioProdottoViewModel>();
            NavigationService.Navigate(new Uri("/DettaglioProdotto.xaml", UriKind.Relative));

            Debug.WriteLine("Invio messaggio");
            Messenger.Default.Send(new NotificationMessage<ProdottoViewModel>(prod, "SelectedProduct"));
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            vm.ClearProducts();
            base.OnNavigatedTo(e);
        }
        private ScrollViewer scrollViewer;

        void ProdottiList_Loaded(object sender, RoutedEventArgs e)
        {
            scrollViewer = GetDescendantByType(lbProducts, typeof(ScrollViewer)) as ScrollViewer;
            if (scrollViewer == null) return;

            FrameworkElement framework = VisualTreeHelper.GetChild(scrollViewer, 0) as FrameworkElement;
            if (framework == null) return;

            VisualStateGroup group = FindVisualState(framework, "ScrollStates");
            if (group == null) return;

            group.CurrentStateChanged += OnListBoxStateChanged;
            vm.LoadProducts();

        }

        private VisualStateGroup FindVisualState(FrameworkElement element, string name)
        {
            if (element == null)
                return null;

            IList groups = VisualStateManager.GetVisualStateGroups(element);
            return groups.Cast<VisualStateGroup>().FirstOrDefault(@group => @group.Name == name);
        }

        public static DependencyObject GetDescendantByType(DependencyObject element, Type type)
        {
            if (element == null)
            {
                return null;
            }
            if (element.GetType() == type)
            {
                return element;
            }
            DependencyObject foundElement = null;
            if (element is FrameworkElement)
            {
               // (element as FrameworkElement).ApplyTemplate();
            }
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++)
            {
                DependencyObject visual = VisualTreeHelper.GetChild(element, i) as DependencyObject;
                foundElement = GetDescendantByType(visual, type);
                if (foundElement != null)
                {
                    break;
                }
            }
            return foundElement;
        }

        private void OnListBoxStateChanged(object sender, VisualStateChangedEventArgs e)
        {

            Debug.WriteLine("Stato: " + e.NewState.Name);
          //  if (e.NewState.Name == "NotScrolling")
            {
                Debug.WriteLine(string.Format("{0}, {1}", scrollViewer.ScrollableHeight, scrollViewer.VerticalOffset));
                if ((int) scrollViewer.ScrollableHeight == (int) scrollViewer.VerticalOffset)
                {
                    vm.LoadProducts();
                }
                // Check the ScrollableHeight and VerticalOffset here to determine
                // the position of the ListBox.
                // Add items, if the ListBox is at the end.

                // This event will fire when the listbox complete stopped it's 
                // scrolling animation
            }
        }
    }
}